#!/usr/bin/env python3
"""
Convert Markdown presentation to PowerPoint (PPTX)
This script provides better control over slide formatting than pandoc
"""

import re
import sys
import os
from pathlib import Path

try:
    from pptx import Presentation
    from pptx.util import Inches, Pt
    from pptx.enum.text import PP_ALIGN
    from pptx.dml.color import RGBColor
except ImportError:
    print("Error: python-pptx library not found")
    print("Install it with: pip install python-pptx")
    sys.exit(1)


def parse_markdown_slides(md_content):
    """Parse markdown content into slides based on ## headers"""
    slides = []
    current_slide = {"title": "", "content": []}
    
    lines = md_content.split('\n')
    
    for line in lines:
        # Check for slide title (## Header)
        if line.startswith('## '):
            # Save previous slide if it has content
            if current_slide["title"] or current_slide["content"]:
                slides.append(current_slide)
            # Start new slide
            current_slide = {
                "title": line[3:].strip(),
                "content": []
            }
        elif line.startswith('### '):
            # Sub-heading
            current_slide["content"].append(("subheading", line[4:].strip()))
        elif line.startswith('- ') or line.startswith('* '):
            # Bullet point
            current_slide["content"].append(("bullet", line[2:].strip()))
        elif line.startswith('**') and line.endswith('**'):
            # Bold text
            current_slide["content"].append(("bold", line.strip('*')))
        elif line.strip() and not line.startswith('---'):
            # Regular text
            current_slide["content"].append(("text", line.strip()))
    
    # Add last slide
    if current_slide["title"] or current_slide["content"]:
        slides.append(current_slide)
    
    return slides


def create_presentation(slides, output_file):
    """Create PowerPoint presentation from parsed slides"""
    prs = Presentation()
    prs.slide_width = Inches(10)
    prs.slide_height = Inches(7.5)
    
    # Define a layout (Title and Content)
    blank_slide_layout = prs.slide_layouts[6]  # Blank layout for more control
    
    for slide_data in slides:
        slide = prs.slides.add_slide(blank_slide_layout)
        
        # Add title
        if slide_data["title"]:
            left = Inches(0.5)
            top = Inches(0.5)
            width = Inches(9)
            height = Inches(1)
            title_box = slide.shapes.add_textbox(left, top, width, height)
            title_frame = title_box.text_frame
            title_frame.text = slide_data["title"]
            title_para = title_frame.paragraphs[0]
            title_para.font.size = Pt(44)
            title_para.font.bold = True
            title_para.alignment = PP_ALIGN.LEFT
        
        # Add content
        if slide_data["content"]:
            left = Inches(0.5)
            top = Inches(1.8)
            width = Inches(9)
            height = Inches(5.5)
            content_box = slide.shapes.add_textbox(left, top, width, height)
            content_frame = content_box.text_frame
            content_frame.word_wrap = True
            
            for content_type, content_text in slide_data["content"]:
                if content_type == "subheading":
                    p = content_frame.add_paragraph()
                    p.text = content_text
                    p.font.size = Pt(32)
                    p.font.bold = True
                    p.space_after = Pt(12)
                elif content_type == "bullet":
                    p = content_frame.add_paragraph()
                    p.text = content_text
                    p.level = 0
                    p.font.size = Pt(18)
                    p.space_after = Pt(6)
                elif content_type == "bold":
                    p = content_frame.add_paragraph()
                    run = p.add_run()
                    run.text = content_text
                    run.font.bold = True
                    run.font.size = Pt(18)
                    p.space_after = Pt(6)
                else:  # text
                    p = content_frame.add_paragraph()
                    p.text = content_text
                    p.font.size = Pt(18)
                    p.space_after = Pt(6)
    
    prs.save(output_file)
    print(f"✓ Successfully created: {output_file}")
    print(f"  Total slides: {len(slides)}")


def main():
    if len(sys.argv) < 2:
        print("Usage: python3 md_to_pptx.py <input.md> [output.pptx]")
        print("Example: python3 md_to_pptx.py ../presentations/project-intro.MD project-intro.pptx")
        sys.exit(1)
    
    input_file = sys.argv[1]
    output_file = sys.argv[2] if len(sys.argv) > 2 else input_file.replace('.md', '.pptx').replace('.MD', '.pptx')
    
    if not os.path.exists(input_file):
        print(f"Error: File '{input_file}' not found")
        sys.exit(1)
    
    print(f"Reading: {input_file}")
    with open(input_file, 'r', encoding='utf-8') as f:
        md_content = f.read()
    
    print("Parsing markdown...")
    slides = parse_markdown_slides(md_content)
    print(f"Found {len(slides)} slides")
    
    print("Creating PowerPoint presentation...")
    create_presentation(slides, output_file)


if __name__ == "__main__":
    main()

